#!/system/bin/sh

set -eu

# 在 Android 应用程序内终端安装 Proot Debian 容器
# 适用于带有 busybox/wget 的 Android 应用程序终端

# 使用 Linux Container 镜像站
URL="https://sgp1lxdmirror01.do.letsbuildthe.cloud/images/debian/bookworm/arm64/default"
REPO="https://gitee.com/hornleaf/a2l/raw/master"
DIR="$HOME/.proot"

: ${WGET:=wget}

[ -d $DIR ] || mkdir -p $DIR

# 下载实用程序（如无 busybox/wget 先从浏览器下载安装）
for i in minitar proot busybox;do
  if [ ! -f $DIR/$i ];then
    $WGET -O $DIR/$i $REPO/$i
  fi
done
cd $DIR
chmod 755 minitar proot busybox
cd $OLDPWD

RUN(){ $DIR/busybox $@;}
TAR(){ $DIR/minitar $@;}


echo "获取版本信息..."
GETTIME=$($WGET -qO - $URL 2>/dev/null | RUN sed -nE 's|.*href="([0-9A-Za-z_%]+)/".*|\1|p' | RUN tail -n1)

[ -f rootfs.tar.xz ] && rm rootfs.tar*
echo "下载镜像..."
$WGET https://down.npee.cn/?$URL/$GETTIME/rootfs.tar.xz

echo "校验镜像完整性"
if [ -z "$($WGET -O - $URL/$GETTIME/SHA256SUMS | grep "$(RUN sha256sum rootfs.tar.xz | awk '{print $1}')")" ];then
  exec echo "校验不通过，请尝试再次安装容器..."
fi

# 解压
echo "正解压镜像..."
RUN xz -d rootfs.tar.xz
echo "正释放镜像..."
mkdir -p $DIR/Debian $DIR/.proot_tmp
mv rootfs.tar $DIR/Debian/
cd $DIR/Debian
TAR -xvf rootfs.tar
RUN rm rootfs.tar
cd $DIR

# 安装 proc
echo "正安装 proc..."
RUN wget $REPO/proc.tar
TAR -xvf proc.tar

# 优化容器
echo "正进行优化操作..."
RUN rm $DIR/Debian/etc/resolv.conf
echo -e "nameserver 8.8.8.8\nnameserver 8.8.4.4" > $DIR/Debian/etc/resolv.conf
echo 'LANG=zh_CN.UTF-8' > $DIR/Debian/etc/locale.conf
sed -i '/en_US.UTF-8 UTF-8/s/#//;/zh_CN.UTF-8 UTF-8/s/#//' $DIR/Debian/etc/locale.gen

# 创建启动脚本
echo -e "#!/system/bin/sh\nPROOT_TMP_DIR=\"$DIR/.proot_tmp\" exec $DIR/proot --sysvipc --link2symlink --kill-on-exit -0 -p -L -H -r $DIR/Debian -b /dev -b /proc -b $DIR/.proot_tmp:/tmp -b /sdcard:/sdcard -b $DIR/proc/loadavg:/proc/loadavg -b $DIR/proc/stat:/proc/stat -b $DIR/proc/version:/proc/version -b $DIR/proc/uptime:/proc/uptime -w /root /usr/bin/env HOME=/root LANG=zh_CN.UTF-8 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin TMPDIR=/tmp COLORTERM=\"${COLORTERM:-truecolor}\" TERM=\"${TERM:-xterm-256color}\" SHELL=/bin/bash SHLVL=\"${SHLVL:-1}\" /bin/bash -l \"\$@\"" | RUN install -m 755 /dev/stdin $DIR/start-debian.sh

[ -f $DIR/start-debian.sh ] && $DIR/start-debian.sh -c locale-gen && echo "执行脚本 $DIR/start-debian.sh 以启动 Proot Debian 容器"
